package com.masz.lcnorder;

import com.alibaba.fastjson.JSONObject;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.codingapi.txlcn.tc.annotation.TccTransaction;
import com.masz.lcnorder.mapper.TbOrder;
import com.masz.lcnorder.mapper.TbOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * @author masz
 * @Date 2022/2/10 11:04
 */

@Service
public class OrderService {

    private static Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    TbOrderMapper mapper;

    @Autowired
    RestTemplate restTemplate;

    @Transactional(rollbackFor = Exception.class)
    @LcnTransaction
    public void add(String orderName) {
        TbOrder o = new TbOrder();
        o.setOrderName(orderName);
        mapper.insert(o);
        JSONObject date = new JSONObject();
        date.put("payName", orderName + "-pay");

        restTemplate.postForEntity("http://lcn-pay/lcnpay/pay", date, String.class);
    }


    /**
     * tcc 分布式事务
     * @param orderName
     */
    @Transactional(rollbackFor = Exception.class)
    @TccTransaction
    public void tccAdd(String orderName) {
        System.out.println("tccAdd");
        TbOrder o = new TbOrder();
        o.setOrderName(orderName);
        mapper.insert(o);
        JSONObject date = new JSONObject();
        date.put("payName", orderName + "-pay");

        restTemplate.postForEntity("http://lcn-pay/lcnpay/payTcc", date, String.class);
    }

    /**
     * tcc 提交  参数需要和 tccAdd 参数一致
     * @param order
     */
    public void confirmTccAdd(String orderName){
        System.out.println("tcc add order confirm:"+orderName);
    }

    /**
     * tcc 回滚
     * @param order
     */
    public void cancelTccAdd(String orderName){
        System.out.println("tcc add order cancel:"+orderName);
        mapper.delByOrderName(orderName);
    }


}
